package com.comon.core.utils;

import lombok.Data;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Random;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2024-01-16
 * Time:10:54
 * Text：
 */

@Data
public class ImageUtil {
    private String str;
    private ByteArrayInputStream image;

    private int width=100;
    private int height=40;

    public void init(){
        Random random=new Random();
        //背景
        final BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
        final Graphics g=image.getGraphics();
        g.setColor(getColor(200,250));
        g.fillRect(0,0,width,height);
        String str2=new String();
        //字体
        g.setFont(new Font("Times News Roman",Font.PLAIN,20));
        for(int i=0;i<4;i++){
            final String rand=String.valueOf(random.nextInt(10));
            str2=str2+rand;
            g.setColor(getColor(20,110));
            g.drawString(rand,(width/6)*i,27);
        }
        str=str2.substring(0);

        for(int i=0;i<150;i++){
            int x=random.nextInt(width);
            int y=random.nextInt(height);
            int x1=random.nextInt(20);
            int y1=random.nextInt(20);
            g.drawLine(x,y,x+x1,y+y1);
        }
        g.dispose();
        ByteArrayInputStream inputStream=null;
        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
        try{
            final ImageOutputStream imageOut= ImageIO.createImageOutputStream(outputStream);
            ImageIO.write(image,"JPEG",imageOut);
            inputStream=new ByteArrayInputStream(outputStream.toByteArray());
        }catch (Exception e){
            System.out.println("生成图片失败");
        }
        this.image=inputStream;
    }
    private Color getColor(int fc ,int bc){
        Random random=new Random();
        if(fc>255){ fc=255;}
        if(bc>255){bc=255;}
        int r=fc+random.nextInt(bc-fc);
        int g=fc+random.nextInt(bc-fc);
        int b=fc+random.nextInt(bc-fc);
        return new Color(r,g,b);
    }
}
